package com.morehair.service.wx.impl;


import com.morehair.bean.bo.wx.SmsBO;
import com.morehair.bean.bo.wx.WxRegisterBO;
import com.morehair.bean.pojo.Coupon;
import com.morehair.bean.pojo.CouponUser;
import com.morehair.bean.pojo.User;
import com.morehair.bean.pojo.UserExample;
import com.morehair.bean.vo.wx.LoginVo;
import com.morehair.bean.vo.wx.WxResetPasswordVO;
import com.morehair.config.MallToken;
import com.morehair.config.component.AliyunComponent;
import com.morehair.mapper.CouponMapper;
import com.morehair.mapper.CouponUserMapper;
import com.morehair.mapper.UserMapper;
import com.morehair.service.wx.WxAuthService;
import com.morehair.utils.Md5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @Description:
 * @Author raohui
 * @Date 2021/6/8 10:20
 */
@Service
@Transactional
public class WxAuthServiceImpl implements WxAuthService {

    @Autowired
    UserMapper userMapper;

    public LoginVo login(String username) {
        Serializable serializable = SecurityUtils.getSubject().getSession().getId();
        //获取sessionId
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        User user = users.get(0);
        LoginVo loginVo = new LoginVo();
        LoginVo.UserInfoDTO userInfo = new LoginVo.UserInfoDTO();
        userInfo.setNickName(user.getNickname());
        userInfo.setAvatarUrl(user.getAvatar());
        loginVo.setUserInfo(userInfo);
        loginVo.setTokenExpire(user.getAddTime());
        loginVo.setToken((String) serializable);
        return loginVo;
    }

    @Autowired
    AliyunComponent aliyunComponent;

    @Override
    public String getSms(SmsBO smsBO) {
        // 生成6位数验证码
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        String mobile = smsBO.getMobile();
        String generatedCode = str.toString();
        aliyunComponent.sendMsg(mobile, generatedCode);
//        generatedCode = "123456";
        return generatedCode;
    }

    @Autowired
    CouponUserMapper couponUserMapper;
    @Autowired
    CouponMapper couponMapper;
    @Override
    public Integer wxRegister(WxRegisterBO registerBO, String generatedCode) throws NoSuchAlgorithmException {
         // 判断验证码
        if ( !registerBO.getCode().equals(generatedCode)) {
            return 0;
        }
        Integer count = userMapper.selectByUsername(registerBO.getUsername());
        if (count != 0) {
            return 1;// 用户名重复
        }
        if (userMapper.selectByPhoneNumber(registerBO.getMobile()) != 0) {
            return 3;
        }
        Date date = new Date();
        String username = registerBO.getUsername();
        String password = Md5Util.getMd5(registerBO.getPassword());
        User user = new User(null, username, password,
                null, null, null, null, null, null,
                registerBO.getMobile(), "https://tu.yaohuo.me/imgs/2021/06/794efa7a3720f65b.png", null, null, date, date, null);
        userMapper.insertSelective(user);
        User latestUser = userMapper.selectLatestUser();
        Integer userId = latestUser.getId();
        // 注册送券
        List<Coupon> registerCoupons = couponMapper.selectByCouponType();
        if (!registerCoupons.isEmpty()) {
            for (Coupon registerCoupon : registerCoupons) {
                Integer total = registerCoupon.getTotal();
                if (total > 0) {
                    Integer couponId = registerCoupon.getId();
                    //  往couponuser里存
                    Short days = registerCoupon.getDays();
                    Calendar rightNow = Calendar.getInstance();
                    Date startTime = rightNow.getTime();
                    rightNow.setTime(date);
                    rightNow.add(Calendar.DAY_OF_YEAR,days);
                    Date endTime=rightNow.getTime();
                    CouponUser couponUser = new CouponUser(null,userId,couponId,registerCoupon.getStatus(),null,startTime,endTime,null,date,date,null);
                    couponUserMapper.insertSelective(couponUser);
                    // 领取一张少一张
                    total--;
                    registerCoupon.setTotal(total);
                    couponMapper.updateByPrimaryKeySelective(registerCoupon);
                }
            }
        }
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return 2;
    }

    @Override
    public Integer resetPassword(WxResetPasswordVO wxResetPasswordVO, String generatedCode) throws NoSuchAlgorithmException {
        // 判断验证码
        if ( !wxResetPasswordVO.getCode().equals(generatedCode)) {
            return 0;
        }
        String password = Md5Util.getMd5(wxResetPasswordVO.getPassword());
        userMapper.updatePassword(wxResetPasswordVO.getMobile(), password);
        return 2;
    }


}
